package utils

import (
	"AiBus/global"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var jwtSecret = []byte(global.App.Configuration.Server.KEY)

type TokenInfo struct {
	OpenID string
}

type MyClaims struct {
	OpenID TokenInfo `json:"open_id"`
	jwt.RegisteredClaims
}

/*生成token*/
func CreateToken(OpenID string) (string, error) {

	tokeninfo := TokenInfo{
		OpenID: OpenID,
	}
	myClaims := MyClaims{
		OpenID: tokeninfo,
		RegisteredClaims: jwt.RegisteredClaims{
			ID: OpenID,

			ExpiresAt: jwt.NewNumericDate(time.Now().Add(3 * time.Hour * time.Duration(1))),
			Issuer:    "local",
		},
	}
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, myClaims)
	signedString, err := claims.SignedString(jwtSecret)
	if err != nil {
		//global.APP.Log.Error(err.Error())
		return "", err
	}
	return signedString, nil
}

/*解析token*/
func ParseToken(token string) (*MyClaims, error) {
	tokenString, err := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}
	// 从tokenClaims中获取到Claims对象，并使用断言，将该对象转换为我们自己定义的Claims
	// 要传入指针，项目中结构体都是用指针传递，节省空间。
	if claims, ok := tokenString.Claims.(*MyClaims); ok && tokenString.Valid {
		return claims, nil
	}
	return nil, err
}
